//
//  SearchHistoryService.m
//  nacf
//
//  Created by liwei on 15/9/30.
//  Copyright © 2015年 liwei. All rights reserved.
//

#import "SearchHistoryService.h"
#import "FMDB.h"
#import "SQLManager.h"

@interface SearchHistoryService() {
    FMDatabaseQueue *q;
}

@end

@implementation SearchHistoryService

- (SearchHistoryService *)init {
    if (self = [super init]) {
        q = [[SQLManager sharedInstance] dbQueue];
    }
    return self;
}

- (NSArray *) queryAllKeyWordWithType:(NSInteger)type {
    NSMutableArray *array = [NSMutableArray array];
    [q inDatabase:^(FMDatabase *db) {
        FMResultSet *rs = [db executeQuery:@"SELECT * FROM SearchHistory where type=? order by _id desc",[NSString stringWithFormat:@"%ld",type]];
        while ([rs next]) {
            NSString *keyword = [rs stringForColumn:@"keyword"];
            [array addObject:keyword];
        }
        [rs close];
    }];
    return array;
}

- (void) insertKeyWordUnique: (NSString *) keyword andType:(NSInteger) type {
    [q inDatabase:^(FMDatabase *db){
        [db executeUpdate:@"delete from SearchHistory where keyword=? and type=?", keyword,[NSString stringWithFormat:@"%ld",type]];
        [db executeUpdate:@"insert into SearchHistory (keyword,type) values (?,?)", keyword,[NSString stringWithFormat:@"%ld",type]];
    }];
}

- (void) removeAllKeyWordWithType:(NSInteger)type {
    [q inDatabase:^(FMDatabase *db){
        [db executeUpdate:@"delete from SearchHistory where type=?",[NSString stringWithFormat:@"%ld",type]];
    }];
}


@end
